package com.xingshang.service.impl;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xingshang.mapper.RecentPlayedMapper;
import com.xingshang.pojo.RecentPlayed;
import com.xingshang.pojo.Song;
import com.xingshang.service.MusicService;
import com.xingshang.utils.JwtHelper;
import com.xingshang.utils.Result;
import com.xingshang.utils.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class MusicServiceImpl implements MusicService {

    @Autowired
    private JwtHelper jwtHelper;

    @Autowired
    private RecentPlayedMapper recentPlayedMapper;

    @Override
    public Result<List<Song>> getSongsFromRankList(String url) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        List<Song> songs = new ArrayList<>();
        List<List<String>> songsList = new ArrayList<>();

        ObjectMapper mapper = new ObjectMapper(); // 只创建一个 ObjectMapper 实例

        try {
            long requestStartTime = System.currentTimeMillis(); // 请求开始时间
            // 发起 GET 请求获取歌曲信息
            HttpResponse response = HttpRequest.get(url)
                    .execute();
            long requestEndTime = System.currentTimeMillis(); // 请求结束时间
            log.info("HTTP 请求耗时：{}ms", requestEndTime - requestStartTime);
            if (response.getStatus() != 200) {
                log.error("请求失败，HTTP状态码：{}", response.getStatus());
                return Result.build(null, ResultCodeEnum.HTTP_REQUEST_ERROR);
            }

            // 解析响应体
            String resp = response.body();
            JsonNode jsonNode = mapper.readTree(resp);
            JsonNode songInfoList = jsonNode.findValue("songInfoList");
//            System.out.println(resp);
            // 解析歌曲信息并构建歌曲列表
            for (JsonNode item : songInfoList) {
                Song song = convertSong(item);
                songs.add(song);
                List<String> songInfo = new ArrayList<>();
                songInfo.add(song.getMid());
                songsList.add(songInfo);
//                song.setIntro(getIntroduction(song.getMid()));
            }
            System.out.println("歌曲数量：" + songs.size());

            // 将封装好的 songsList 转换为 JSON 字符串
            String jsonData = mapper.writeValueAsString(Collections.singletonMap("songs", songsList));
            long s = System.currentTimeMillis();
//            System.out.println(jsonData);
            // 发起 POST 请求
            HttpResponse response1 = HttpRequest.post("https://qq-music-api-main.vercel.app/batchGetSongInfo")
                    .header("Content-Type", "application/json")  // 设置 Content-Type 为 application/json
                    .body(jsonData)
                    .execute();
            long e = System.currentTimeMillis();
            log.info("HTTP 请求耗时：{}ms", e - s);
            if (response1.getStatus() == 200) {
                String resp1 = response1.body();
//                System.out.println(resp1);
                JsonNode jsonNode1 = mapper.readTree(resp1);
                JsonNode data = jsonNode1.get("data");

                // 提取数据并设置 intro
                for (int i = 0; i < data.size(); i++) {
                    JsonNode data1 = data.get(i);
                    JsonNode songInfoNode = data1.get("songinfo");

                    // 提取 intro，避免多次使用 path 查找
                    if (songInfoNode != null) {
                        JsonNode introNode = songInfoNode.path("data").path("info").path("intro").path("content");
                        if (introNode.isArray() && !introNode.isEmpty()) {
                            // 获取 intro，如果没有则设置默认值
                            String intro = introNode.get(0).path("value").asText("暂无简介");
                            songs.get(i).setIntro(intro);
                        } else {
                            songs.get(i).setIntro("暂无简介");
                        }
                    } else {
                        songs.get(i).setIntro("暂无简介");
                    }
                }
            }
            long endTime = System.currentTimeMillis();
            log.info("转换耗时：{}ms", endTime - e);

        } catch (Exception e) {
            log.error("获取歌曲列表失败", e);
            return Result.build(null, ResultCodeEnum.SYSTEM_ERROR);
        }

        return Result.ok(songs);
    }


    private Song convertSong(JsonNode obj) {
        // 从传入的 JSONObject 获取歌曲信息
        Song song = new Song();

        // 获取 id
        song.setSongId(obj.get("id").asInt());

        // 获取专辑信息中的 mid
        JsonNode albumJson = obj.get("album");
        song.setAlbumMid(albumJson.get("mid").asText());

        // 获取歌曲标题
        song.setTitle(obj.get("title").asText());

        // 获取歌手信息，并将所有歌手的名字用 "/" 链接

        JsonNode singers = obj.get("singer");
        if (singers != null && !singers.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (JsonNode singer : singers) {
                sb.append(singer.get("name").asText()).append("/");
            }
            song.setSingerName(sb.substring(0, sb.length() - 1));
        }
        // 获取封面图片 URL
        song.setCover("https://y.qq.com/music/photo_new/T002R300x300M000" + song.getAlbumMid() + ".jpg?max_age=2592000");
        song.setMid(obj.get("mid").asText());

        return song;
    }


    /**
     * 根据传入的mid获取歌词
     *
     * @param songMid
     * @return
     */
    @Override
    public List<JSONObject> fetchLyric(String songMid) {
        String url = "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?songmid=" + songMid + "&format=json&nobase64=1";

        HttpResponse response = HttpRequest.get(url)
                .header("Referer", "https://y.qq.com/portal/player.html")
                .header("Host", "y.qq.com")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .header("Accept-Encoding", "gzip, deflate, br, zstd")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .execute();

        List<JSONObject> lyricsList = new ArrayList<>();

        if (response.getStatus() == 200) {
            String resp = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(resp);
            Object lyric = jsonObject.getByPath("lyric");
            if (lyric == null) {
                return null;
            }
            // 分析LRC格式的歌词并转换为JSON对象列表
            String lyricText = lyric.toString();
            String[] lines = lyricText.split("\n");

            for (String line : lines) {
                // 只提取歌词文本部分，去掉时间戳（例如 [00:00.00]）
                int index = line.indexOf("]");
                if (index > -1) {
                    String time = line.substring(1, index); // 提取时间戳
                    String text = line.substring(index + 1).trim(); // 提取歌词文本
                    if (text.isEmpty()) continue;
                    // 将歌词和时间封装成一个JSONObject
                    JSONObject lyricJson = new JSONObject();
                    lyricJson.put("name", text);
                    lyricJson.put("time", time);

                    // 添加到歌词列表中
                    lyricsList.add(lyricJson);
                }
            }
        }

        return lyricsList;
    }

    @Override
    public Result getSongInfo(String songMid, Integer q, String token) throws JsonProcessingException {
        Long userId = jwtHelper.getUserId(token);
        RecentPlayed recentPlayed = new RecentPlayed();
        JsonNode songInfoByMid = this.getSongInfoByMid(songMid);
//        String url = "https://api.lolimi.cn/API/qqdg/?mid=" + songMid + "&q=" + q;
        String url = "https://qq-music-api-main.vercel.app/getMusicPlay?songmid=" + songMid + "&resType=play&quality=flac";

        HttpResponse response = HttpRequest.get(url).execute();
        HashMap<String, Object> data = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        if (null != songInfoByMid) {
            data.put("mid", songMid);
            data.put("lyric", fetchLyric(songMid));//单独获取歌词
            data.put("id", songInfoByMid.get("id").asInt());
            data.put("song", songInfoByMid.get("title").asText());
            data.put("singer", songInfoByMid.get("singer").get(0).get("name"));
            data.put("album", songInfoByMid.get("album").get("name").asText());
            //"https://y.qq.com/music/photo_new/T002R300x300M000" + song.getAlbumMid() + ".jpg?max_age=2592000"
            data.put("cover", "https://y.qq.com/music/photo_new/T002R300x300M000" + songInfoByMid.get("album").get("mid").asText() + ".jpg?max_age=2592000");
            if (response.getStatus() == 200) {
                String resp = response.body();
                System.out.println(resp);
                JsonNode jsonNode = mapper.readTree(resp);
                String url1 = jsonNode.findPath("url").asText();
                data.put("url", url1);
                recentPlayed.setUserid(userId.intValue());
                recentPlayed.setMid(songMid);
                recentPlayed.setCover(data.get("cover").toString());
                recentPlayed.setTitle(data.get("song").toString());
                int insert = recentPlayedMapper.insert(recentPlayed);

            }
            return Result.ok(data);
        }

        return Result.build(null, ResultCodeEnum.NULL_DATA);
    }

    @Override
    public Result getSongListBySearch(String keyword) {
        String url = "https://qq-music-api-main.vercel.app/getSearchByKey?key=" + keyword;
        HttpResponse response = HttpRequest.get(url).execute();
        ObjectMapper mapper = new ObjectMapper();
        if (response.getStatus() == 200) {
            String resp = response.body();
            try {
                JsonNode jsonNode = mapper.readTree(resp);

                //response.data.song.list
                JsonNode dataNode = jsonNode.findValue("data");
                JsonNode songNode = dataNode.findValue("song");
                JsonNode listNode = songNode.findValue("list");

                System.out.println(listNode);
                return Result.ok(listNode);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return Result.build(null, ResultCodeEnum.NULL_DATA);
    }

    @Override
    public Result getRecomPlaylist() {
        String url = "https://qq-music-api-main.vercel.app/getRecommend";
        HttpResponse response = HttpRequest.get(url).execute();
        ObjectMapper mapper = new ObjectMapper();
        if (response.getStatus() == 200) {
            String resp = response.body();
            try {
                JsonNode jsonNode = mapper.readTree(resp);
                JsonNode dataNode = jsonNode.findValue("v_hot");
//                System.out.println(dataNode);
                return Result.ok(dataNode);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

        }
        return Result.build(null, ResultCodeEnum.NULL_DATA);
    }

    @Override
    public Result getCategory(String id) {
        String url = "https://qq-music-api-main.vercel.app/getSongLists?categoryId=" + id;
        HttpResponse response = HttpRequest.get(url).execute();
        if (response.getStatus() == 200) {
            String resp = response.body();
            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonNode jsonNode = mapper.readTree(resp);
                System.out.println(jsonNode);
                JsonNode dataNode = jsonNode.findValue("response").findValue("data").findValue("list");
                return Result.ok(dataNode);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

        }
        return Result.build(null, ResultCodeEnum.NULL_DATA);
    }

    @Override
    public Result getHotSearch() {
        // 定义请求的 URL
        String url = "https://u.y.qq.com/cgi-bin/musicu.fcg";

        // 构造请求的 JSON 数据
        String jsonBody = """
                {
                    "hotkey": {
                        "module": "tencent_musicsoso_hotkey.HotkeyService",
                        "method": "GetHotkey",
                        "param": {
                            "client_type": 25,
                            "remote_place": "txt.miniapp.wxada7aab80ba27074",
                            "search_id": "1734610348633",
                            "uin": "1152921504867780058"
                        }
                    }
                }
                """;

        try {
            // 发送 POST 请求
            HttpResponse response = HttpRequest.post(url)
                    .header("Host", "u.y.qq.com")
                    .header("Connection", "keep-alive")
                    .header("Content-Type", "application/json")
                    .header("Accept-Encoding", "gzip,compress,br,deflate")
                    .header("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.53(0x18003531) NetType/4G Language/zh_CN")
                    .header("Referer", "https://servicewechat.com/wxada7aab80ba27074/114/page-frame.html")
                    .body(jsonBody)
                    .execute();

            // 检查响应状态
            if (response.getStatus() == 200) {
                String resp = response.body();
                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonNode = mapper.readTree(resp);
                JsonNode dataNode = jsonNode.findValue("vec_hotkey");

                // 打印结果用于调试
                System.out.println(dataNode);

                // 返回结果封装
                return Result.ok(dataNode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 返回空数据的默认结果
        return Result.build(null, ResultCodeEnum.NULL_DATA);
    }


    public JsonNode getSongInfoByMid(String songMid) throws JsonProcessingException {
        //https://qq-music-api-main.vercel.app/getSongInfo?songmid=004fneUm24gD2c
        String url = "https://qq-music-api-main.vercel.app/getSongInfo?songmid=" + songMid;

        HttpResponse response = HttpRequest.get(url)
                .execute();
        ObjectMapper mapper = new ObjectMapper();
        if (response.getStatus() == 200) {
            String resp1 = response.body();
            JsonNode jsonNode = mapper.readTree(resp1);
            JsonNode trackInfo = jsonNode.findPath("track_info");
            return trackInfo;
        }
        return null;
    }
}
